import 'dart:convert';
import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:image_saver/image_saver.dart';
import 'package:panda/base/SignType.dart';
import 'package:panda/entity/article_list_entity.dart';
import 'package:panda/http/Api.dart';
import 'package:panda/http/HttpUtil.dart';
import 'package:panda/set/ArticleDetail.dart';
import 'package:panda/util/AppSaveInfoUtil.dart';
import 'package:panda/util/LoadingUtil.dart';
import 'package:panda/util/SignUtil.dart';
import 'package:path_provider/path_provider.dart';
import 'package:url_launcher/url_launcher.dart';

import '../base/Constant.dart';

class MaterialCenterPage extends StatefulWidget {
  int type = 0;
  String goods_id;
  MaterialCenterPage({Key key, this.type, this.goods_id}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return MaterialCenterView();
  }
}

class MaterialCenterView extends State<MaterialCenterPage> {
  List<HomeListDataData> dataList = new List();
  int page = 1;
  String token = "";
  EasyRefreshController _controller = EasyRefreshController();
  String name = "";
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getString(TOKEN).then((value) {
      token = value;
    });
    loadList();
  }

  loadList() async {
    Map map = new Map();
    map['cat_id'] = widget.type == 0 ? "7" : "8";
    map['p'] = page.toString();
    map['per'] = "10";
    if (widget.goods_id != null) {
      map['type_value'] = widget.goods_id;
    }
    map['search'] = name;
    map['sign_type'] = SignType.GET_ARTICLE_LIST;
    Response<String> response =
        await HttpUtil().post(Api.GET_SYSTEM_ARTICLE, data: getSign(map));
    print(map);
    Map userMap = json.decode(response.data);
    HomeListEntity homeServiceEntity = new HomeListEntity.fromJson(userMap);
    if (userMap['code'] == 1 && mounted) {
      if (page == 1) {
        dataList.clear();
        _controller.resetLoadState();
        _controller.finishRefresh();
      } else {
        _controller.finishLoad(
            noMore: homeServiceEntity.data.datas.length == 0);
        if (homeServiceEntity.data.datas.length == 0) {
          Fluttertoast.showToast(msg: "已经加载全部");
        }
      }
      dataList.addAll(homeServiceEntity.data.datas);
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);

    return new Scaffold(
      appBar: new AppBar(
        title: Text(widget.type == 0 ? '素材中心' : "熊猫社区",
            style: TextStyle(
                fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE),
                color: Colors.black)),
        backgroundColor: Colors.white,
        brightness: Brightness.light,
        centerTitle: true,
        iconTheme: new IconThemeData(color: Colors.black),
        elevation: 0.5,
      ),
      body: new Container(
        color: white,
        child: Column(
          children: <Widget>[
            Container(
              padding: EdgeInsets.all(10),
              color: f0Color,
              child: Row(
                children: <Widget>[
                  Expanded(
                    flex: 1,
                    child: Container(
                      margin: EdgeInsets.fromLTRB(
                          ScreenUtil.getInstance().setHeight(DP_10),
                          0,
                          ScreenUtil.getInstance().setHeight(DP_10),
                          0),
                      height: ScreenUtil.getInstance().setHeight(DP_60),
                      decoration: BoxDecoration(
                          color: white,
                          borderRadius: BorderRadius.circular(20.0)),
                      child: ConstrainedBox(
                        constraints: BoxConstraints(maxHeight: DP_80),
                        child: TextField(
                          keyboardAppearance: Brightness.light,
                          maxLines: 1,
                          onChanged: (value) {
                            name = value;
                          },
                          style: TextStyle(
                              color: Colors.black45,
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(NORMAL_FONT_SIZE)),
                          cursorColor: mainColor,
                          decoration: new InputDecoration(
                              // contentPadding: EdgeInsets.all(0),
                              prefixIcon: Icon(
                                Icons.search,
                                color: Colors.black45,
                              ),
                              hintText: "输入文字搜索",
                              border: InputBorder.none,
                              hintStyle: TextStyle(
                                  color: Colors.black45,
                                  fontSize: ScreenUtil.getInstance()
                                      .setSp(NORMAL_FONT_SIZE))),
                        ),
                      ),
                    ),
                  ),
                  GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    child: Container(
                        alignment: Alignment.center,
                        width: ScreenUtil.getInstance().setWidth(DP_80),
                        child: Text('搜索',
                            style: TextStyle(
                                color: black_99,
                                fontSize: ScreenUtil.getInstance()
                                    .setSp(NORMAL_FONT_SIZE)))),
                    onTap: () {
                      page = 1;
                      loadList();
                    },
                  )
                ],
              ),
            ),
            Expanded(
                child: new EasyRefresh(
              header: MaterialHeader(),
              footer: MaterialFooter(),
              enableControlFinishRefresh: true,
              enableControlFinishLoad: true,
              controller: _controller,
              child: ListView.separated(
                  itemBuilder: _renderRow,
                  separatorBuilder: (BuildContext context, int index) {
                    return Container(
                        color: divideColor,
                        height: ScreenUtil.getInstance().setHeight(DP_20));
                  },
                  itemCount: dataList.length),
              onRefresh: () async {
                page = 1;
                loadList();
              },
              onLoad: () async {
                page++;
                loadList();
              },
            ))
          ],
        ),
      ),
    );
  }

  Widget _renderRow(BuildContext context, int index) {
    return new GestureDetector(
      child: Container(
        color: white,
        padding: EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_20)),
        child: new Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            Row(
              children: <Widget>[
                Container(
                  height: ScreenUtil.getInstance().setHeight(DP_60 + 5),
                  width: ScreenUtil.getInstance().setHeight(DP_60 + 5),
                  padding: EdgeInsets.all(1),
                  child: ClipOval(
                    child: Image.asset(
                      "images/app_icon.png",
                      width: ScreenUtil.getInstance().setHeight(DP_50 + 5),
                      height: ScreenUtil.getInstance().setHeight(DP_50 + 5),
                    ),
                  ),
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(
                          ScreenUtil.getInstance().setHeight(DP_60 + 5)),
                      border: Border.all(color: black_99, width: 1)),
                ),
                Container(width: ScreenUtil.getInstance().setHeight(DP_20)),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      dataList[index].author == ""
                          ? "熊猫新零售"
                          : dataList[index].author,
                      style: TextStyle(
                          fontSize: ScreenUtil.getInstance()
                              .setSp(NORMAL_FONT_SIZE + 3),
                          color: black),
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                    Container(
                        height: ScreenUtil.getInstance().setHeight(DP_8 / 2)),
                    Text(
                      dataList[index].pubtime,
                      style: TextStyle(
                          fontSize:
                              ScreenUtil.getInstance().setSp(MINI_FONT_SIZE),
                          color: Colors.black45),
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ],
                ),
                Expanded(
                  child: Center(),
                ),
                new Container(
                  width: ScreenUtil.getInstance().setWidth(DP_120 + DP_20),
                  padding: EdgeInsets.all(4),
                  decoration: new BoxDecoration(
                      color: Colors.red[50],
                      borderRadius: BorderRadius.circular(10)),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Image.asset("images/icon_share.png"),
                      Container(
                        width: ScreenUtil.getInstance().setHeight(DP_10),
                      ),
                      new Text(
                        dataList[index].clicknum,
                        style: new TextStyle(
                            color: Colors.red[200],
                            fontSize: ScreenUtil.getInstance()
                                .setSp(SMALL_FONT_SIZE)),
                      ),
                    ],
                  ),
                )
              ],
            ),
            Container(height: ScreenUtil.getInstance().setHeight(DP_10)),
            Html(
              defaultTextStyle: TextStyle(color: black_99, letterSpacing: 2),
              data: dataList[index].title,
            ),
            Container(height: ScreenUtil.getInstance().setHeight(DP_10)),
            GridView.builder(
              shrinkWrap: true,
              padding: EdgeInsets.only(top: 0),
              physics: new NeverScrollableScrollPhysics(),
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 3,
                  mainAxisSpacing: ScreenUtil.getInstance().setHeight(DP_10),
                  crossAxisSpacing: ScreenUtil.getInstance().setHeight(DP_10),
                  childAspectRatio: 1),
              itemBuilder: (BuildContext context, int index1) {
                return CachedNetworkImage(
                    imageUrl:
                        dataList[index].imglists[index1].contains("upload")
                            ? Api.BaseUrl + dataList[index].imglists[index1]
                            : Api.ImgBaseUrl + dataList[index].imglists[index1],
                    width: (MediaQuery.of(context).size.width -
                            ScreenUtil.getInstance().setHeight(DP_60)) /
                        3,
                    fit: BoxFit.cover,
                    height: (MediaQuery.of(context).size.width -
                            ScreenUtil.getInstance().setHeight(DP_60)) /
                        3);
              },
              itemCount: dataList[index].imglists.length > 9
                  ? 9
                  : dataList[index].imglists.length,
            ),
            Container(height: ScreenUtil.getInstance().setHeight(DP_15)),
            // Container(
            //   padding:
            //       EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_15)),
            //   decoration: BoxDecoration(
            //       borderRadius: BorderRadius.circular(3), color: f0Color),
            //   child: Row(
            //     children: <Widget>[
            //       ClipRRect(
            //         borderRadius: BorderRadius.circular(5),
            //         child: CachedNetworkImage(
            // imageUrl:
            //             "https://dss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=1663653008,3382974478&fm=26&gp=0.jpg",
            //             width: ScreenUtil.getInstance().setHeight(DP_60 + 10),
            //             fit: BoxFit.cover,
            //             height: ScreenUtil.getInstance().setHeight(DP_60 + 10)),
            //       ),
            //       Container(width: ScreenUtil.getInstance().setHeight(DP_15)),
            //       Expanded(
            //         child: Text(
            //           '雅诗兰黛 Estee Lauder 密集修护维稳5件套（安瓶精华20ml+棕瓶50ml+中样*3+随机礼盒）',
            //           maxLines: 2,
            //           style: TextStyle(
            //               letterSpacing: 2,
            //               fontSize:
            //                   ScreenUtil.getInstance().setSp(MINI_FONT_SIZE),
            //               color: black_99),
            //           overflow: TextOverflow.ellipsis,
            //         ),
            //       ),
            //       Container(width: ScreenUtil.getInstance().setHeight(DP_15)),
            //       Icon(Icons.arrow_forward_ios,
            //           color: Colors.black45,
            //           size: ScreenUtil.getInstance().setHeight(DP_30))
            //     ],
            //   ),
            // ),
            // Container(height: ScreenUtil.getInstance().setHeight(DP_15)),
            Row(
              children: <Widget>[
                Expanded(
                  child: Center(),
                ),
                GestureDetector(
                  child: new Container(
                    padding: EdgeInsets.fromLTRB(
                        ScreenUtil.getInstance().setHeight(15),
                        5,
                        ScreenUtil.getInstance().setHeight(15),
                        5),
                    decoration: new BoxDecoration(
                        color: mainColor,
                        borderRadius: BorderRadius.circular(10)),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Image.asset("images/icon_forward.png"),
                        Container(
                          width: ScreenUtil.getInstance().setHeight(5),
                        ),
                        new Text(
                          "复制文案",
                          style: new TextStyle(
                              color: white,
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(MINI_FONT_SIZE)),
                        ),
                      ],
                    ),
                  ),
                  onTap: () async {
                    ClipboardData data =
                        new ClipboardData(text: dataList[index].title);
                    Clipboard.setData(data);
                    Fluttertoast.showToast(msg: "文案已复制");
                    // if (dataList[index].imglists.length > 0)
                    //   down(0, dataList[index].imglists.length, index);
                  },
                  behavior: HitTestBehavior.opaque,
                ),
                GestureDetector(
                  child: new Container(
                    padding: EdgeInsets.fromLTRB(
                        ScreenUtil.getInstance().setHeight(15),
                        5,
                        ScreenUtil.getInstance().setHeight(15),
                        5),
                    margin: EdgeInsets.only(left: 10),
                    decoration: new BoxDecoration(
                        color: mainColor,
                        borderRadius: BorderRadius.circular(10)),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Image.asset("images/icon_forward.png"),
                        Container(
                          width: ScreenUtil.getInstance().setHeight(5),
                        ),
                        new Text(
                          "一键保存",
                          style: new TextStyle(
                              color: white,
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(MINI_FONT_SIZE)),
                        ),
                      ],
                    ),
                  ),
                  onTap: () async {
                    ClipboardData data =
                        new ClipboardData(text: dataList[index].title);
                    Clipboard.setData(data);
                    if (dataList[index].imglists.length > 0)
                      down(0, dataList[index].imglists.length, index);
                  },
                  behavior: HitTestBehavior.opaque,
                )
              ],
            ),
          ],
        ),
      ),
      onTap: () {
        Navigator.of(context).push(MaterialPageRoute(builder: (context) {
          return new ArticleDetailPage(
            article_id: dataList[index].article_id,
          );
        }));
      },
    );
  }

  down(index, size, j) async {
    if (index == size) {
      return;
    }
    Directory dic;
    if (Platform.isAndroid) {
      dic = await getExternalStorageDirectory();
      String path = dic.path + "/xiongmao";
      bool has = await Directory(path).exists();
      if (!has) {
        await Directory(path).create();
      }
    } else {
      dic = await getApplicationDocumentsDirectory();
    }
    // for (int i = 0; i < dataList[index].imglists.length; i++) {
    String imgPath = dataList[j].imglists[index].contains("upload")
        ? Api.BaseUrl + dataList[j].imglists[index]
        : Api.ImgBaseUrl + dataList[index].imglists[index];
    if (Platform.isAndroid) {
      downloadFile(
          imgPath,
          dic.path +
              "/xiongmao" +
              "/" +
              DateTime.now().millisecondsSinceEpoch.toString() +
              ".png",
          index == (size - 1),
          index == 0,
          index,
          size,
          j);
    } else {
      downloadFile(
          imgPath,
          dic.path +
              "/" +
              DateTime.now().millisecondsSinceEpoch.toString() +
              ".png",
          index == (size - 1),
          index == 0,
          index,
          size,
          j);
    }

    // }
  }

  /*
   * 下载文件
   */
  downloadFile(urlPath, savePath, finals, start, index, size, j) async {
    if (start)
      showDialog(
          context: context,
          barrierDismissible: false,
          builder: (_) {
            return new NetLoadingDialog(
              loadingText: "保存中...",
              bgColor: Color.fromARGB(255, 0, 0, 0),
              requestCallBack: null,
              outsideDismiss: false,
            );
          });
    Dio dio = Dio();
    dio.options.responseType = ResponseType.bytes;
    var response = await dio.get(urlPath);
    File savedFile;
    // savedFile = await ImageGallerySaver.saveImage(response.data)
    savedFile = await File(savePath).writeAsBytes(response.data);
    if (savedFile != null) {
      await ImageGallerySaver.saveFile(savePath);
      index = index + 1;
      down(index, size, j);
      if (finals) {
        Navigator.of(context).pop(1);
        // Fluttertoast.showToast(msg: "文案，图片已自动保存!");
        showDialog(
          context: context,
          builder: (context) => new AlertDialog(
            title: new Text('提示'),
            content: new Text('文案已自动复制，图片已自动保存'),
            actions: <Widget>[
              // new FlatButton(
              //   onPressed: () => Navigator.of(context).pop(false),
              //   child: new Text(
              //     '取消',
              //     style: TextStyle(color: Colors.grey),
              //   ),
              // ),
              new FlatButton(
                onPressed: () {
                  Navigator.of(context).pop(false);
                  // open();
                },
                child: new Text('知道了', style: TextStyle(color: mainColor)),
              ),
            ],
          ),
        );
      }
    }
  }

  open() {
    const url = "weixin://";
    launch(url);
  }
}
